/**
 * 文章栏目弹出框
 * 
 * 用于新增新的文章栏目，编辑文章栏目
 * 
 */

import React, { Component, PropTypes } from 'react';
import { Form, Select, Input, InputNumber, Modal } from 'antd'
import { List, Map } from 'immutable'
const FormItem = Form.Item;
const Option = Select.Option

const noop = () => {}
class SectionDialog extends Component {

    static propTypes = {
        onOk:PropTypes.func,
        onCancel:PropTypes.func,
        section:PropTypes.object
    }
    static defaultProps = {
        onOk:noop,
        onCancel:noop,
        section:Map({}),//需要编辑的栏目数据
        visible:false,
        title:'',
        options:List.of(),//顶级栏目选项列表
        activeId:'',//当前选中新增的子栏目或编辑的栏目
    }
    componentWillReceiveProps(nextProps) {
        if(this.props.visible !== nextProps.visible && !nextProps.visible){
            this.props.form.resetFields();
        }
    }
    
    render() {
        const { visible, form, options, activeId, section } = this.props;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 18 },
        };
        const inputStyle = { width:220, marginRight: 5}

        let hiddenId = null;
        if(section.get('id')){
            //编辑栏目，就要创造一个hidden的input
            hiddenId = form.getFieldDecorator('id',{
                initialValue:section.get('id')
            })(
                <Input type="hidden" />
            )
        }
        //栏目名称
        const nameField = form.getFieldDecorator('sname',{
            initialValue: section.get('sname') || '',
            rules:[
                {required:true,pattern:/[\w\d\u4e00-\u9fa5]/m,message:"请输入栏目名称"},
                {type:"string",min:1,max:10,message:"栏目名称限制1-10字"}
            ]
        })(
            <Input placeholder="" style={inputStyle} />
        )
        let defaultPid = '0';
        if(options.count() > 0){
            if(section.get('id')){
                //编辑状态
                defaultPid = section.get('pid');
            }else if(activeId){
                //新增子栏目状态
                defaultPid = options.find(item=>item.get('id') === activeId) ? activeId : defaultPid;
            }
        }
        //上级栏目
        const pidField = form.getFieldDecorator('pid',{
            initialValue:defaultPid.toString()
        })(
             <Select size="large" style={inputStyle}>
                <Option value="0" key="0">-无-（顶级类目请选“无”）</Option>
                {options.map(option=>(<Option key={option.get('id')} value={option.get('id').toString()}>{option.get('sname')}</Option>))}
            </Select>
        )

        /**
         * 自定义url
         * 1.新增的时候，可填项，因为后台自动根据名称拼音添加该字段
         * 2.编辑的时候，必填；不能为空
         */
        let urlRules = [
            {type:"string",max:50,min:1,message:"自定义域名限制1-64字"},
            { pattern:/^(\/\w+){1}$/,message:"自定义域名格式错误,例：/abc"}
        ];
        let urlRequired = false;

        if(section.get('id')){
            //编辑状态
            urlRules.push(
                {
                    type:"string",required:true,message:"请输入自定义域名"
                }
            )
            urlRequired = true;
        }
        const urlField = form.getFieldDecorator('url',{
            initialValue: section.get('url') || '',
            rules:urlRules
        })(
             <Input placeholder="" style={inputStyle} />
        )

        //栏目排序
        const sortField = form.getFieldDecorator('sort',{
            initialValue: section.get('sort') || 999,
            rules:[
                {
                    validator:this.validateSort
                },
            ]
        })(
            <InputNumber placeholder="" style={inputStyle} min={1} max={999} />
        )
        return (
            <Modal
                title="新增栏目"
                visible={visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                width="800px"
            >
                <Form>
                    <div className="add-article-dialog">
                        <div className="block-fff">
                            {hiddenId}
                            <FormItem
                                label="栏目名称"
                                {...formItemLayout}
                                required
                            >
                                {nameField}
                            </FormItem>

                            <FormItem
                                label="上级栏目"
                                {...formItemLayout}
                            >
                               {pidField}
                            </FormItem>

                            <FormItem
                                label="自定义url"
                                {...formItemLayout}
                                extra="无需填入您的域名前缀，不填则默认为栏目名称的拼音全拼"
                                required={urlRequired}
                            >
                               {urlField}
                            </FormItem>
                            <FormItem
                                label="栏目排序"
                                {...formItemLayout}
                                required
                            >
                                {sortField}
                                <span className="ant-form-text"> 数值越小越靠前</span>
                            </FormItem>
                        </div>
                    </div>
                </Form>
            </Modal>
            
        );
    }

    validateSort = (rule, value, callback)=>{
        if(!value){
            callback("请输入栏目排序");
        }else if(!/^\d{1,3}$/.test(value)){
            callback("栏目排序限制为数字类型:1-3位")
        }else{
            callback();
        }
    }
    /**
     * 确定按钮回调
     */
    handleOk = () => {
        const { onOk, form, section } = this.props;
        //验证输入值
        form.validateFields((err,fieldsValue)=>{
            if(err){
                return;
            }
            
            onOk(fieldsValue)
        })
    }
    /**
     * 取消按钮回调
     */
    handleCancel = () => {
        const { onCancel, form} = this.props;
        onCancel()
        //重置初始值
        //form.resetFields();
    }
}

const FormSectionDialog = Form.create()(SectionDialog)

export default FormSectionDialog;